package com.sj.purchase.modules.cost.config.task.synchronizedata;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sj.purchase.modules.cost.repository.imei.InventoryRepository;
import com.sj.purchase.modules.cost.domain.imei.Inventory;
import com.sj.purchase.modules.cost.domain.imei.InventoryId;
import com.sj.purchase.util.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * Created by yangrd on 2017/10/16
 **/
@Component
class InventoryTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(InventoryTask.class);

    @Value("${sj.ecwms}")
    private String ecwmsApi;

    @Autowired
    private InventoryRepository repository;

    @Autowired
    private RestTemplate restTemplate;

    private static String FORMAT = "yyyy/MM/dd";

    /**
     * yyyy/MM/dd
     *
     * @param day
     */
    @Transactional
    public void synchronizeInventory(String day) {
        if (repository.count() < 1) {
            List<Inventory> list = initInventoryList();
            repository.save(list);
        } else {
            Date tomorrow = null;
            try {
                tomorrow = DateUtils.addDays(DateUtils.parseDate(day, FORMAT), 1);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            String endDate = DateFormatUtils.format(tomorrow, FORMAT);
            //同步入库串码
            repository.save(listInStockImei(day, endDate));
            LOGGER.debug("[{}--{}]:=>同步入库串码", day, endDate);
            //同步出库串码
            repository.save(listOutStockImei(day, endDate));
            LOGGER.debug("[{}--{}]:=>同步出库串码", day, endDate);
        }
    }

    /**
     * 初始化现有库存
     */
    private List<Inventory> initInventoryList() {
        String jsonStr = restTemplate.getForObject(ecwmsApi + "/imei", String.class);
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        return jsonArray.stream().map(this::parseInventory).collect(Collectors.toList());
    }

    /**
     * @param start yyyy/MM/dd
     * @param end   yyyy/MM/dd
     * @return
     */
    private List<Inventory> listInStockImei(String start, String end) {
        String jsonStr = restTemplate.getForObject(ecwmsApi + "/inbound-serial-no?start=" + start + "&end=" + end, String.class);
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        return jsonArray.stream().map(this::parseInventory).collect(Collectors.toList());
    }

    /**
     * @param start yyyy/MM/dd
     * @param end   yyyy/MM/dd
     * @return
     */
    private List<Inventory> listOutStockImei(String start, String end) {
        String jsonStr = restTemplate.getForObject(ecwmsApi + "/outbound-serial-no?start=" + start + "&end=" + end, String.class);
        JSONArray jsonArray = JSONArray.parseArray(jsonStr);
        return jsonArray.stream().map(o -> {
            JSONObject jsonObject = (JSONObject) o;
            String imei = jsonObject.getString("imei");
            String shipNo = jsonObject.getString("shipNo");
            String orderNo = jsonObject.getString("orderNo");
            Date createDate = jsonObject.getDate("createDate");
            String shopName = jsonObject.getString("shopName");
            Inventory inventory = repository.findFirstById_ImeiOrderById_InStockDateDesc(imei);
            if (Objects.nonNull(inventory)) {
                inventory.setOutShipNo(shipNo).setOutOrderNo(orderNo).setOutStockDate(createDate).setShopName(shopName);
            }
            return inventory;
        }).filter(Objects::nonNull).collect(Collectors.toList());
    }

    private Inventory parseInventory(Object obj) {
        JSONObject jsonObject = (JSONObject) obj;
        String imei = jsonObject.getString("imei");
        String skuName = jsonObject.getString("skuName");
        String referNo = jsonObject.getString("referNo");//参考单
        Double costPrice = jsonObject.getDouble("price");//成本价
        String inOrderNo = jsonObject.getString("orderNo");//入库单
        Date inStockDate = jsonObject.getDate("createDate");//入库日期
        String spuNo = jsonObject.getString("productNo");
        String skuNo = jsonObject.getString("skuNo");
        return new Inventory(
                new InventoryId(imei, inStockDate),
                skuName,
                referNo,
                costPrice,
                inOrderNo,
                spuNo,
                skuNo
        );
    }
}
